﻿    /*Copyright (C) 2013 Brian D. Allred
     *
     *This program is free software: you can redistribute it and/or modify
     *it under the terms of the GNU General Public License as published by
     *the Free Software Foundation.
	 *
     *A copy of this license can be found at:
	
     *    https://www.gnu.org/copyleft/gpl.html

     *This program is distributed in the hope that it will be useful,
     *but WITHOUT ANY WARRANTY; without even the implied warranty of
     *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     *GNU General Public License for more details.

     *You should have received a copy of the GNU General Public License
     *along with this program.  If not, see <http://www.gnu.org/licenses/>.
     */

using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using AutoBackup.Properties;

namespace AutoBackup
{
    public partial class Form1 : Form
    {
        private readonly Timer _backupTimer = new Timer();
        private readonly Timer _startTimer = new Timer();
        private DateTime _currentTime;
        private string _dest;
        private bool _goodCopy;
        private TimeSpan _interval;
        private bool _isStart;
        private string[] _lines = new string[6];
        private bool _loadedFromStartup;
        private string _selected;
        private string _source;
        private string _time;

        public Form1()
        {
            InitializeComponent();
            SetupForm(true);
        }

        private void SetupForm(bool firstRun)
        {
            string period;
            bool am = false;
            _currentTime = DateTime.Now;
            string currentTimeShortString = _currentTime.ToShortTimeString();
            int hour = Convert.ToInt32(currentTimeShortString.Substring(0, currentTimeShortString.IndexOf(":")));
            int min = Convert.ToInt32(currentTimeShortString.Substring(currentTimeShortString.IndexOf(":") + 1, 2));
            if (currentTimeShortString.Contains("A"))
            {
                am = true;
                period = "AM";
            }
            else
            {
                period = "PM";
            }
            SetupIntervals(hour, min, period, am);
            if (firstRun)
            {
                FirstRun();
                if (_loadedFromStartup && _lines.Length == 6)
                {
                    TimeSpan startSpan;
                    CheckBoxStartup.Checked = true;
                    int startMin = 0;
                    if (_lines[3].Contains("at"))
                    {
                        startMin = Convert.ToInt32(_lines[3].Substring(_lines[3].IndexOf(':') + 1, 2));
                    }
                    if (_lines[3].Contains("Run now"))
                    {
                        DirectoryCopy();
                        DeleteArchives();
                    }
                    if (!TimeSpan.TryParse(TextBoxInterval.Text, out startSpan))
                    {
                        if (TextBoxInterval.Text.Equals("Enter backup interval here..."))
                        {
                            NotifyIcon.BalloonTipTitle = Resources.Form1_SetupForm_No_settings_to_load_;
                            NotifyIcon.BalloonTipText =
                                Resources.Form1_SetupForm_No_settings_were_found_or_they_haven_t_been_set_yet_;
                            _loadedFromStartup = false;
                        }
                        else
                        {
                            MessageBox.Show(Resources.Form1_SetupForm_Can_t_load_some_settings_,
                                Resources.Form1_SetupForm_Startup_Error_, MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                            _loadedFromStartup = false;
                        }
                        return;
                    }
                    if (_lines[3].Contains("interval now"))
                    {
                        _backupTimer.Interval = Convert.ToInt32(startSpan.TotalMilliseconds);
                        _backupTimer.Tick += BackupHandler;
                        _backupTimer.Start();
                        NotifyIcon.BalloonTipTitle = Resources.Form1_SetupForm_Loaded_from_settings_;
                        NotifyIcon.BalloonTipText = Resources.Form1_SetupForm_Backups_set_to_occur_every_ +
                                                    startSpan.ToString().Substring(0, startSpan.ToString().Length - 3) +
                                                    Resources.Form1_SetupForm__;
                        _interval = startSpan;
                        CheckBoxStartup.Enabled = false;
                        TextBoxInterval.Enabled = false;
                        ComboBoxDelete.Enabled = false;
                        ComboBoxIntervals.Enabled = false;
                        DeleteArchives();
                        ToolStrip_Stop.Enabled = true;
                        ButtonStartStop.Text = Resources.Form1_SetupForm_Stop_;
                        return;
                    }
                    int minDiff = (startMin >= min) ? startMin - min : startMin - min + 60;
                    TimeSpan span = (minDiff > 9) ? TimeSpan.Parse("0:" + minDiff) : TimeSpan.Parse("0:0" + minDiff);
                    DateTime start = DateTime.Now;
                    start = start.Add(span);
                    start = start.AddSeconds(-start.Second);
                    TimeSpan countDown = start.Subtract(_currentTime);
                    _isStart = false;
                    _startTimer.Interval = Convert.ToInt32(countDown.TotalMilliseconds);
                    _startTimer.Tick += StartHandler;
                    _startTimer.Start();
                    CheckBoxStartup.Enabled = false;
                    TextBoxInterval.Enabled = false;
                    ComboBoxDelete.Enabled = false;
                    ComboBoxIntervals.Enabled = false;
                    DeleteArchives();
                    ToolStrip_Stop.Enabled = true;
                    ButtonStartStop.Text = Resources.Form1_SetupForm_Stop_;
                    NotifyIcon.BalloonTipTitle = Resources.Form1_SetupForm_Loaded_from_settings_;
                    _interval = startSpan;
                    NotifyIcon.BalloonTipText = Resources.Form1_SetupForm_Backups_set_to_start_at_ +
                                                start.ToShortTimeString() + Resources.Form1_SetupForm__and_occur_every_ +
                                                _interval.ToString().Substring(0, _interval.ToString().Length - 3) +
                                                Resources.Form1_SetupForm__;
                }
            }
            else
            {
                foreach (object obj in ComboBoxIntervals.Items)
                {
                    if (obj.ToString().Equals(_selected))
                    {
                        ComboBoxIntervals.SelectedItem = _selected;
                    }
                }
                if (ComboBoxIntervals.SelectedItem == null)
                {
                    ComboBoxIntervals.SelectedItem = "Run now";
                }
            }
        }

        private void SetupIntervals(int hour, int min, string period, bool am)
        {
            if (ComboBoxIntervals.SelectedItem != null)
            {
                _selected = ComboBoxIntervals.SelectedItem.ToString();
            }
            while (ComboBoxIntervals.Items.Count > 0)
            {
                ComboBoxIntervals.Items.RemoveAt(0);
            }
            ComboBoxIntervals.Items.Add("Run now");
            ComboBoxIntervals.Items.Add("Run now, start interval now");
            ComboBoxIntervals.Items.Add("Start interval now");
            if (min < 15)
            {
                ComboBoxIntervals.Items.Add("Run now, start interval at " + hour + ":15 " + period);
                ComboBoxIntervals.Items.Add("Start interval at " + hour + ":15 " + period);
                ComboBoxIntervals.Items.Add("Run now, start interval at " + hour + ":30 " + period);
                ComboBoxIntervals.Items.Add("Start interval at " + hour + ":30 " + period);
                if (hour == 11 && am)
                {
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:00 PM");
                }
                else if (hour == 11)
                {
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                }
                else
                {
                    if (hour == 12)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 1:00 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at 1:00 " + period);
                    }
                    else
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at " + (hour + 1) + ":00 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at " + (hour + 1) + ":00 " + period);
                    }
                }
                if (am)
                {
                    bool noon = false;
                    bool midnight = false;
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 PM"))
                        {
                            noon = true;
                        }
                    }
                    if (!noon)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 PM");
                    }
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 AM"))
                        {
                            midnight = true;
                        }
                    }
                    if (!midnight)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                    }
                }
                else
                {
                    bool noon = false;
                    bool midnight = false;
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 AM"))
                        {
                            midnight = true;
                        }
                    }
                    if (!midnight)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                    }
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 PM"))
                        {
                            noon = true;
                        }
                    }
                    if (!noon)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM tomorrow");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 PM tomorrow");
                    }
                }
            }
            else if (min < 30)
            {
                ComboBoxIntervals.Items.Add("Run now, start interval at " + hour + ":30 " + period);
                ComboBoxIntervals.Items.Add("Start interval at " + hour + ":30 " + period);
                if (hour == 11 && am)
                {
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:00 PM");
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:15 PM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:15 PM");
                }
                else if (hour == 11)
                {
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:15 AM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:15 AM");
                }
                else
                {
                    if (hour == 12)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 1:00 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at 1:00 " + period);
                        ComboBoxIntervals.Items.Add("Run now, start interval at 1:15 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at 1:15 " + period);
                    }
                    else
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at " + (hour + 1) + ":00 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at " + (hour + 1) + ":00 " + period);
                        ComboBoxIntervals.Items.Add("Run now, start interval at " + (hour + 1) + ":15 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at " + (hour + 1) + ":15 " + period);
                    }
                }
                if (am)
                {
                    bool noon = false;
                    bool midnight = false;
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 PM"))
                        {
                            noon = true;
                        }
                    }
                    if (!noon)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 PM");
                    }
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 AM"))
                        {
                            midnight = true;
                        }
                    }
                    if (!midnight)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                    }
                }
                else
                {
                    bool noon = false;
                    bool midnight = false;
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 AM"))
                        {
                            midnight = true;
                        }
                    }
                    if (!midnight)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                    }
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 PM"))
                        {
                            noon = true;
                        }
                    }
                    if (!noon)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM tomorrow");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 PM tomorrow");
                    }
                }
            }
            else if (min < 45)
            {
                ComboBoxIntervals.Items.Add("Run now, start interval at " + hour + ":45 " + period);
                ComboBoxIntervals.Items.Add("Start interval at " + hour + ":45 " + period);
                if (hour == 11 && am)
                {
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:00 PM");
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:30 PM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:30 PM");
                }
                else if (hour == 11)
                {
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:30 AM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:30 AM");
                }
                else
                {
                    if (hour == 12)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 1:00 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at 1:00 " + period);
                        ComboBoxIntervals.Items.Add("Run now, start interval at 1:30 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at 1:30 " + period);
                    }
                    else
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at " + (hour + 1) + ":00 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at " + (hour + 1) + ":00 " + period);
                        ComboBoxIntervals.Items.Add("Run now, start interval at " + (hour + 1) + ":30 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at " + (hour + 1) + ":30 " + period);
                    }
                }
                if (am)
                {
                    bool noon = false;
                    bool midnight = false;
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 PM"))
                        {
                            noon = true;
                        }
                    }
                    if (!noon)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 PM");
                    }
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 AM"))
                        {
                            midnight = true;
                        }
                    }
                    if (!midnight)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                    }
                }
                else
                {
                    bool noon = false;
                    bool midnight = false;
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 AM"))
                        {
                            midnight = true;
                        }
                    }
                    if (!midnight)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                    }
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 PM"))
                        {
                            noon = true;
                        }
                    }
                    if (!noon)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM tomorrow");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 PM tomorrow");
                    }
                }
            }
            else
            {
                if (hour == 11 && am)
                {
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:00 PM");
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:15 PM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:15 PM");
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:30 PM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:30 PM");
                }
                else if (hour == 11)
                {
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:15 AM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:15 AM");
                    ComboBoxIntervals.Items.Add("Run now, start interval at 12:30 AM");
                    ComboBoxIntervals.Items.Add("Start interval at 12:30 AM");
                }
                else
                {
                    if (hour == 12)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 1:00 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at 1:00 " + period);
                        ComboBoxIntervals.Items.Add("Run now, start interval at 1:15 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at 1:15 " + period);
                        ComboBoxIntervals.Items.Add("Run now, start interval at 1:30 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at 1:30 " + period);
                    }
                    else
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at " + (hour + 1) + ":00 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at " + (hour + 1) + ":00 " + period);
                        ComboBoxIntervals.Items.Add("Run now, start interval at " + (hour + 1) + ":15 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at " + (hour + 1) + ":15 " + period);
                        ComboBoxIntervals.Items.Add("Run now, start interval at " + (hour + 1) + ":30 " + period);
                        ComboBoxIntervals.Items.Add("Start interval at " + (hour + 1) + ":30 " + period);
                    }
                }
                if (am)
                {
                    bool noon = false;
                    bool midnight = false;
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 PM"))
                        {
                            noon = true;
                        }
                    }
                    if (!noon)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 PM");
                    }
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 AM"))
                        {
                            midnight = true;
                        }
                    }
                    if (!midnight)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                    }
                }
                else
                {
                    bool noon = false;
                    bool midnight = false;
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 AM"))
                        {
                            midnight = true;
                        }
                    }
                    if (!midnight)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 AM");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 AM");
                    }
                    foreach (object obj in ComboBoxIntervals.Items)
                    {
                        if (obj.ToString().Contains("12:00 PM"))
                        {
                            noon = true;
                        }
                    }
                    if (!noon)
                    {
                        ComboBoxIntervals.Items.Add("Run now, start interval at 12:00 PM tomorrow");
                        ComboBoxIntervals.Items.Add("Start interval at 12:00 PM tomorrow");
                    }
                }
            }
        }

        private void FirstRun()
        {
            try
            {
                string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                appDataPath += "\\AutoBackup\\settings.ini";
                using (var sr = new StreamReader(appDataPath))
                {
                    string line = sr.ReadToEnd();
                    string[] separators = {"\n", "\r"};
                    _lines = line.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                    if (_lines.Length == 4 || _lines.Length == 6)
                    {
                        if (_lines.Length == 6)
                        {
                            FolderSource.SelectedPath = _lines[0];
                            LabelSource.Text = _lines[0];
                            _source = _lines[0];
                            FolderDest.SelectedPath = _lines[1];
                            LabelDest.Text = _lines[1];
                            _dest = _lines[1];
                            TextBoxInterval.Text = _lines[2];
                            foreach (object obj in ComboBoxIntervals.Items)
                            {
                                if (obj.ToString().Equals(_lines[3]))
                                {
                                    ComboBoxIntervals.SelectedItem = _lines[3];
                                }
                            }
                            if (ComboBoxIntervals.SelectedItem == null)
                            {
                                ComboBoxIntervals.SelectedItem = "Run now";
                            }
                            ComboBoxDelete.SelectedItem = _lines[4];
                            if (_lines[5].Equals("yes"))
                            {
                                _loadedFromStartup = true;
                            }
                            else
                            {
                                CheckBoxStartup.Checked = false;
                            }
                        }
                        else
                        {
                            TextBoxInterval.Text = _lines[0];
                            foreach (object obj in ComboBoxIntervals.Items)
                            {
                                if (obj.ToString().Equals(_lines[1]))
                                {
                                    ComboBoxIntervals.SelectedItem = _lines[1];
                                }
                            }
                            if (ComboBoxIntervals.SelectedItem == null)
                            {
                                ComboBoxIntervals.SelectedItem = "Run now";
                            }
                            ComboBoxDelete.SelectedItem = _lines[2];
                            if (_lines[3].Equals("yes"))
                            {
                                _loadedFromStartup = true;
                            }
                        }
                    }
                    else
                    {
                        throw new Exception();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                ComboBoxIntervals.SelectedItem = "Run now";
                ComboBoxDelete.SelectedItem = "Never delete archives";
            }
        }

        private void LabelSource_Click(object sender, EventArgs e)
        {
            if (FolderSource.ShowDialog() == DialogResult.OK)
            {
                LabelSource.Text = FolderSource.SelectedPath;
                if (LabelDest.Text.Equals("Click here to choose destination directory..."))
                {
                    FolderDest.SelectedPath = FolderSource.SelectedPath;
                }
            }
        }

        private void LabelDest_Click(object sender, EventArgs e)
        {
            if (FolderDest.ShowDialog() == DialogResult.OK)
            {
                LabelDest.Text = FolderDest.SelectedPath;
                if (LabelSource.Text.Equals("Click here to choose source directory..."))
                {
                    FolderSource.SelectedPath = FolderDest.SelectedPath;
                }
            }
        }

        private void ButtonStartStop_Click(object sender, EventArgs e)
        {
            _interval = TimeSpan.Parse("1:00");
            string run = ComboBoxIntervals.SelectedItem.ToString();
            _source = LabelSource.Text;
            _dest = LabelDest.Text;
            if (ButtonStartStop.Text.Equals(Resources.Form1_ButtonStartStop_Click_Start_))
            {
                if (CheckErrors(run))
                {
                    ButtonStartStop.Text = Resources.Form1_SetupForm_Stop_;
                    if (run.Contains("Run now"))
                    {
                        DirectoryCopy();
                        DeleteArchives();
                        if (run.Equals("Run now"))
                        {
                            ButtonStartStop.Text = Resources.Form1_ButtonStartStop_Click_Start_;
                        }
                    }
                    if (run.Contains("at"))
                    {
                        _time = run.Substring(run.LastIndexOf("at") + 3);
                        StartTimers();
                    }
                    else if (run.ToLower().Contains("start"))
                    {
                        _time = "now";
                        StartTimers();
                    }
                }
            }
            else
            {
                _backupTimer.Stop();
                _startTimer.Stop();
                ButtonStartStop.Text = Resources.Form1_ButtonStartStop_Click_Start_;
                SetupForm(false);
                TextBoxInterval.Enabled = true;
                ComboBoxDelete.Enabled = true;
                ComboBoxIntervals.Enabled = true;
                ToolStrip_Stop.Enabled = false;
                CheckBoxStartup.Enabled = true;
            }
        }

        private void StartTimers()
        {
            CopyTimer();
            TextBoxInterval.Enabled = false;
            ComboBoxDelete.Enabled = false;
            ComboBoxIntervals.Enabled = false;
            DeleteArchives();
            ToolStrip_Stop.Enabled = true;
            if (_time.Equals("now"))
            {
                NotifyIcon.BalloonTipText = Resources.Form1_SetupForm_Backups_set_to_occur_every_ +
                                            _interval.ToString().Substring(0, _interval.ToString().Length - 3) +
                                            Resources.Form1_StartTimers__;
                NotifyIcon.BalloonTipTitle = Resources.Form1_StartTimers_Backups_Started_;
            }
            else
            {
                NotifyIcon.BalloonTipText = Resources.Form1_SetupForm_Backups_set_to_start_at_ + _time +
                                            Resources.Form1_SetupForm__and_occur_every_ +
                                            _interval.ToString().Substring(0, _interval.ToString().Length - 3) +
                                            Resources.Form1_StartTimers__;
                NotifyIcon.BalloonTipTitle = Resources.Form1_StartTimers_Backups_Scheduled_;
            }
            WindowState = FormWindowState.Minimized;
        }

        private bool CheckErrors(string run)
        {
            if (_source.Equals("Click here to choose source directory..."))
            {
                MessageBox.Show(Resources.Form1_CheckErrors_Must_select_a_source_directory_);
                return false;
            }
            if (_dest.Equals("Click here to choose destination directory..."))
            {
                MessageBox.Show(Resources.Form1_CheckErrors_Must_select_a_destination_directory_);
                return false;
            }
            if (ComboBoxIntervals.SelectedItem == null)
            {
                MessageBox.Show(Resources.Form1_CheckErrors_Must_select_a_backup_run_interval_option_);
                return false;
            }
            if (!(run.Equals("Run now") || TimeSpan.TryParse(TextBoxInterval.Text, out _interval)))
            {
                MessageBox.Show(Resources.Form1_CheckErrors_Must_enter_backup_interval_as_a_valid_time_);
                return false;
            }
            return true;
        }

        private void CopyTimer()
        {
            if (_time.Equals("now"))
            {
                _backupTimer.Interval = Convert.ToInt32(_interval.TotalMilliseconds);
                _backupTimer.Tick += BackupHandler;
                _backupTimer.Start();
            }
            else
            {
                _currentTime = DateTime.Now;
                if (_time.Equals(_currentTime.ToShortTimeString()))
                {
                    _backupTimer.Interval = Convert.ToInt32(_interval.TotalMilliseconds);
                    _backupTimer.Tick += BackupHandler;
                    _backupTimer.Start();
                    DirectoryCopy();
                    DeleteArchives();
                }
                else
                {
                    DateTime time = DateTime.Now;
                    double hoursDiff = time.Hour;
                    double minDiff = time.Minute;
                    double selectedHour = Convert.ToDouble(_time.Substring(0, _time.IndexOf(':')));
                    double selectedMin = Convert.ToDouble(_time.Substring(_time.IndexOf(':') + 1, 2));
                    bool selectedAM = (_time.Contains("AM"));
                    bool currentAM = (time.ToShortTimeString().Contains("AM"));
                    if ((int) selectedHour == 12)
                    {
                        if (selectedAM)
                        {
                            if (currentAM && minDiff <= selectedMin)
                            {
                                selectedHour = 0;
                            }
                            else
                            {
                                selectedHour += 12;
                            }
                        }
                    }
                    else if (!selectedAM)
                    {
                        selectedHour += 12;
                    }
                    hoursDiff = selectedHour - hoursDiff;
                    if (hoursDiff < 0)
                    {
                        hoursDiff += 24;
                    }
                    minDiff = selectedMin - minDiff;
                    if (minDiff < 0)
                    {
                        hoursDiff -= 1;
                        minDiff += 60;
                    }
                    TimeSpan span = (minDiff >= 10)
                        ? TimeSpan.Parse(hoursDiff + ":" + minDiff)
                        : TimeSpan.Parse(hoursDiff + ":0" + minDiff);
                    DateTime start = time.Add(span);
                    start = start.AddSeconds(-start.Second);
                    TimeSpan countDown = start.Subtract(_currentTime);
                    _isStart = false;
                    _startTimer.Interval = Convert.ToInt32(countDown.TotalMilliseconds);
                    _startTimer.Tick += StartHandler;
                    _startTimer.Start();
                }
            }
        }

        private void DirectoryCopy()
        {
            try
            {
                // Get the subdirectories for the specified directory.
                var dir = new DirectoryInfo(_source);
                DirectoryInfo[] dirs = dir.GetDirectories();
                string dest1 = _dest + "\\" + DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss");

                if (!dir.Exists)
                {
                    throw new DirectoryNotFoundException(
                        "Source directory does not exist or could not be found: "
                        + _source);
                }

                // If the destination directory doesn't exist, create it. 
                if (!Directory.Exists(dest1))
                {
                    Directory.CreateDirectory(dest1);
                }

                // Get the files in the directory and copy them to the new location.
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    string temppath = Path.Combine(dest1, file.Name);
                    file.CopyTo(temppath, true);
                }

                // If copying subdirectories, copy them and their contents to new location. 
                if (true)
                {
                    foreach (DirectoryInfo subdir in dirs)
                    {
                        string temppath = Path.Combine(dest1, subdir.Name);
                        DirectoryCopy(subdir.FullName, temppath, true);
                    }
                }
                _goodCopy = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                if (e.Message.Contains("Could not find a part of the path"))
                {
                    DialogResult result = MessageBox.Show(Resources.Form1_DirectoryCopy_,
                        Resources.Form1_BackupHandler_Error_, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                    if (result == DialogResult.Yes)
                    {
                        DirectoryCopy();
                    }
                }
                _goodCopy = false;
            }
        }

        private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            try
            {
                // Get the subdirectories for the specified directory.
                var dir = new DirectoryInfo(sourceDirName);
                DirectoryInfo[] dirs = dir.GetDirectories();

                if (!dir.Exists)
                {
                    throw new DirectoryNotFoundException(
                        "Source directory does not exist or could not be found: "
                        + sourceDirName);
                }

                // If the destination directory doesn't exist, create it. 
                if (!Directory.Exists(destDirName))
                {
                    Directory.CreateDirectory(destDirName);
                }

                // Get the files in the directory and copy them to the new location.
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    string temppath = Path.Combine(destDirName, file.Name);
                    file.CopyTo(temppath, true);
                }

                // If copying subdirectories, copy them and their contents to new location. 
                if (copySubDirs)
                {
                    foreach (DirectoryInfo subdir in dirs)
                    {
                        string temppath = Path.Combine(destDirName, subdir.Name);
                        DirectoryCopy(subdir.FullName, temppath, true);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private void BackupHandler(object obj, EventArgs ea)
        {
            DeleteArchives();
            DirectoryCopy();
            if (_goodCopy)
            {
                NotifyIcon.BalloonTipText = Resources.Form1_SetupForm_Backups_set_to_occur_every_ +
                                            _interval.ToString().Substring(0, _interval.ToString().Length - 3) +
                                            Resources.Form1_BackupHandler__;
                NotifyIcon.BalloonTipTitle = Resources.Form1_BackupHandler_Backup_successful_;
            }
            else
            {
                NotifyIcon.BalloonTipText = Resources.Form1_BackupHandler_Error_occured_during_copy_;
                NotifyIcon.BalloonTipTitle = Resources.Form1_BackupHandler_Error_;
                ButtonStartStop_Click(null, null);
                Show();
                WindowState = FormWindowState.Normal;
            }
            NotifyIcon.ShowBalloonTip(50);
        }

        private void StartHandler(object obj, EventArgs ea)
        {
            if (!_isStart)
            {
                _backupTimer.Interval = Convert.ToInt32(_interval.TotalMilliseconds);
                _backupTimer.Tick += BackupHandler;
                _backupTimer.Start();
                _startTimer.Stop();
                DeleteArchives();
                DirectoryCopy();
                _isStart = true;
                NotifyIcon.BalloonTipText = Resources.Form1_SetupForm_Backups_set_to_occur_every_ +
                                            _interval.ToString().Substring(0, _interval.ToString().Length - 3) +
                                            Resources.Form1_StartHandler__;
                NotifyIcon.BalloonTipTitle = Resources.Form1_StartTimers_Backups_Started_;
                NotifyIcon.ShowBalloonTip(50);
            }
        }

        private void DeleteArchives()
        {
            string delete = ComboBoxDelete.SelectedItem.ToString();
            string[] delimiters = {"\n", "\r", " "};
            string[] deleteTokens = delete.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            int deleteN = Convert.ToInt32(deleteTokens[deleteTokens.Length - 2]);
            string deleteType = deleteTokens[deleteTokens.Length - 1];
            if (delete.Contains("Never"))
            {
                return;
            }
            try
            {
                var dir = new DirectoryInfo(_dest);
                DirectoryInfo[] dirs = dir.GetDirectories();
                foreach (DirectoryInfo subDir in dirs)
                {
                    try
                    {
                        DateTime now = DateTime.Now;
                        string folderName = subDir.Name;
                        char[] chars = folderName.ToCharArray();
                        chars[folderName.LastIndexOf('-')] = ':';
                        chars[folderName.LastIndexOf('-', folderName.LastIndexOf('-') - 1)] = ':';
                        chars[folderName.IndexOf('T')] = ' ';
                        folderName = new string(chars);
                        DateTime folder = DateTime.Parse(folderName);
                        TimeSpan time = now.Subtract(folder);
                        DirectoryDelete(subDir.FullName, deleteN, deleteType, time);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private void DirectoryDelete(string fullName, int deleteN, string deleteType, TimeSpan time)
        {
            if (deleteType.Contains("day") && time.TotalDays >= deleteN)
            {
                Directory.Delete(fullName, true);
            }
            else if (deleteType.Contains("month") && time.TotalDays >= (deleteN*30))
            {
                Directory.Delete(fullName, true);
            }
            else if (deleteType.Contains("year") && time.TotalDays >= (deleteN*365))
            {
                Directory.Delete(fullName, true);
            }
        }

        private void ComboBoxIntervals_SelectedIndexChanged(object sender, EventArgs e)
        {
            TextBoxInterval.Enabled = !ComboBoxIntervals.SelectedItem.ToString().Equals("Run now");
        }

        public string EndProgram()
        {
            var lines = new string[6];
            _source = LabelSource.Text;
            _dest = LabelDest.Text;
            string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            appDataPath += "\\AutoBackup\\";
            if (_backupTimer.Enabled)
            {
                _backupTimer.Stop();
            }
            try
            {
                lines[0] = _source;
                lines[1] = _dest;
                lines[2] = TextBoxInterval.Text;
                lines[3] = ComboBoxIntervals.SelectedItem.ToString();
                lines[4] = ComboBoxDelete.SelectedItem.ToString();
                if (CheckBoxStartup.Checked)
                {
                    lines[5] = "yes";
                    AppShortcutToStartup(true);
                }
                else
                {
                    lines[5] = "no";
                    AppShortcutToStartup(false);
                }
                Directory.CreateDirectory(appDataPath);
                File.WriteAllLines(appDataPath + "settings.ini", lines);
                return "";
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            string error = EndProgram();
            if (!error.Equals(""))
            {
                Console.WriteLine(error);
            }
        }

        private void TextBoxInterval_Click(object sender, EventArgs e)
        {
            if (TextBoxInterval.Text.Equals("Enter backup interval here..."))
            {
                TextBoxInterval.Text = "";
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState)
            {
                Hide();
                NotifyIcon.Visible = true;
                NotifyIcon.ShowBalloonTip(50);
            }

            else if (FormWindowState.Normal == WindowState)
            {
                NotifyIcon.Visible = false;
            }
        }

        private void NotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;
        }

        private void ToolStrip_Exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void ToolStrip_Stop_Click(object sender, EventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;
            ButtonStartStop_Click(null, null);
        }

        private static void AppShortcutToStartup(bool create)
        {
            string dir = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            try
            {
                if (create)
                {
                    using (var writer = new StreamWriter(dir + "\\AutoBackup.url"))
                    {
                        string app = Assembly.GetExecutingAssembly().Location;
                        writer.WriteLine("[InternetShortcut]");
                        writer.WriteLine("URL=file:///" + app);
                        writer.WriteLine("IconIndex=0");
                        string icon = app.Replace('\\', '/');
                        writer.WriteLine("IconFile=" + icon);
                        writer.Flush();
                    }
                }
                else
                {
                    File.Delete(dir + "\\AutoBackup.url");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            if (_loadedFromStartup)
            {
                WindowState = FormWindowState.Minimized;
            }
        }
    }
}